// mircoApp/activityClock/clockCalendar/clockCalendar.js
const app = getApp();
const skinBehavior = require("../../../utils/themeSkin/skinBehavior");
Page({

  /**
   * 页面的初始数据
   */
  behaviors: [skinBehavior],
  data: {
    minDate:'',
    maxDate: '',
    sixMonthsAgoDate:'',
    recordShow:false,
    recordData:[],
    timeTitle:'',
    iPnoneBottomBol:'',
    id:'',
    query:{
      admin_type:1,
      id:'',
      page_type:1
    },
    partInfo:{},
    calendarInfo:{},
    //判断打卡，补卡的状态，今日打卡状态为1，今日未打卡状态状态为2，需要补卡状态为3
    dateStatus:0,
    recordDataTest:[],
    //补卡ID
    reissueId:'',
    dayStatus:true,
    activityInfo:{},
    pluginId:'',
    defDate:new Date().getTime(),
    imgPath:app.globalData.imgPath
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    if(options.id) {
      this.setData({
        id:options.id,
        'query.id':options.id
      })
    }
    let yz_basic_info = wx.getStorageSync("yz_basic_info");
    if(yz_basic_info) {
      this.setData({
        pluginId:yz_basic_info.plugin_setting?.check_in_rebate?.plugin_id
      })
    }
    this.maxMonthsAgo();
    this.calculateSixMonthsAgo();

    this.getiPnoneBottom();
  },
  
  recordColse() {
    this.setData({
      recordShow: false
    })
  },
   //打卡活动记录参加打卡接口
  partCheck() {
    wx.navigateTo({
      url: `/mircoApp/activityClock/clockAdd/clockAdd?id=${this.data.query.id}&type=0&pluginid=${this.data.pluginId}&goodsId=${this.data.partInfo.goods_id}&orderId=${this.data.partInfo.order_id}`,
    })
  },
  //打卡活动记录参加补卡打卡接口
  reissueOn() {
    wx.navigateTo({
      url: `/mircoApp/activityClock/clockAdd/clockAdd?id=${this.data.query.id}&type=0&pluginid=${this.data.pluginId}&goodsId=${this.data.partInfo.goods_id}&orderId=${this.data.partInfo.order_id}&actId=${this.data.activityInfo.id}&reissueId=${this.data.reissueId}`,
    })
  },
  formatters(day) {
    let now = new Date();
    let toMonth = now.getMonth() + 1;
    let toDay = now.getDate();
    const month = day.date.getMonth() + 1;
    const date = day.date.getDate();
    //获取打卡开始日期
    if(this.data.recordData && this.data.recordData.length > 0) {
      this.data.recordData.map((item,index) => {
        let time =  new Date(item.created_at);
        let recordMonth = time.getMonth() + 1;
        if(toMonth == month && toDay == date && (time.getDate() != date 
        && !this.data.dayStatus)) {
          day.text = '今';
          day.className = 'current-class';
        }
        if((recordMonth ==  month && time.getDate() == date) && item.status == 2 && item.check_in_type == 2 ) {
          //补卡样式
          day.bottomInfo = '补卡';
          day.className = 'reissue-class';
        }
        if((recordMonth ==  month && time.getDate() == date) && item.status == 1 && item.check_in_type == 1 ) {
          day.className = 'today-class';
          day.text = date;
        }
      });
    }
    return day;
  },
  //最小日期
  calculateSixMonthsAgo() {
    const currentDate = new Date(); // 获取当前日期
    const sixMonthsAgoDate = new Date(currentDate); // 复制当前日期
    // 设置六个月前的日期
    sixMonthsAgoDate.setMonth(currentDate.getMonth() - 1);
    // 设置时间为 0 点 0 分 0 秒
    sixMonthsAgoDate.setHours(0, 0, 0, 0);
    // // 将六个月前的日期格式化为可读的字符串
    let minDate = sixMonthsAgoDate.getTime(); // 格式化为字符串
    this.setData({
      minDate:minDate
    })
  },
  maxMonthsAgo() {
    const currentDate = new Date(); // 获取当前日期
    const sixMonthsAgoDate = new Date(currentDate); // 复制当前日期
    // 设置六个月前的日期
    sixMonthsAgoDate.setMonth(currentDate.getMonth() + 1);
    // 设置时间为 0 点 0 分 0 秒
    sixMonthsAgoDate.setHours(0, 0, 0, 0);
    // // 将六个月前的日期格式化为可读的字符串
    let maxDate = sixMonthsAgoDate.getTime(); // 格式化为字符串
    this.setData({
      maxDate:maxDate
    })
  },
  calendarChange(event) {
    let timestampToTime = this.timestampToTime(new Date(event.detail).getTime());
    this.setData({
      recordDataTest:[]
    })
     //选择的日期
    let selectTime = new Date(event.detail);
    let month = selectTime.getMonth() + 1

    //今天的日期
    let now = new Date();
    let toMonth = now.getMonth() + 1;
    let toDay = now.getDate();

    //获取活动开始日期和结束日期的区间;
    let endTime = new Date(this.data.partInfo?.activity?.end_time).getTime();
    let startTime = new Date(this.data.partInfo?.activity?.start_time).getTime();
    let currentTime = new Date().getTime();
    if((currentTime >= startTime && currentTime <= endTime)) { //判断在活动时间内
      this.data.timeTitle = timestampToTime;
      if(this.data.recordData.length > 0) {
        this.data.recordData.map((item,index) => {
          let time =  new Date(item.created_at);
          let recordMonth = time.getMonth() + 1;
          //判断记录列表有没有补卡的日期
          //今日没有打卡，去跳转打卡
          //判断打卡，补卡的状态，今日打卡状态为1，今日未打卡状态状态为2，需要补卡状态为3
          if(toMonth == month && toDay == selectTime.getDate() && (time.getDate() != selectTime.getDate()  
          && !this.data.dayStatus)) {
            //第二次连续打卡，不在活动详情打卡，在打卡日历打卡的情况
            this.data.recordShow = true;
            this.data.dateStatus = 2;
          } else if((time.getDate() == selectTime.getDate()) 
            && item.status == 1 && item.check_in_type == 1) {
              this.data.recordShow = true;
              this.data.dateStatus = 1;
              this.data.recordDataTest.push(this.data.recordData[index]);
          } else if((recordMonth ==  month && time.getDate() == selectTime.getDate()) 
            && item.status == 2 && item.check_in_type == 2) {
              //补卡功能
              this.data.dateStatus = 3;
              this.data.recordShow = true;
              this.data.reissueId = this.data.recordData[index].activity?.supplement_goods_id;
              this.data.activityInfo = this.data.recordData[index];
              this.data.recordDataTest.push(this.data.recordData[index]);
          } else {
            console.log(event);
            // app.tips('打卡错误');
          }
        });
        this.setData({
          recordShow:this.data.recordShow,
          timeTitle:this.data.timeTitle,
          dateStatus:this.data.dateStatus,
          reissueId:this.data.reissueId,
          recordDataTest:this.data.recordDataTest,
          activityInfo:this.data.activityInfo
        })
      }
    }
  },
  //日期转化
  timestampToTime(timestamp) {
    var date = new Date(timestamp);
    let Y = date.getFullYear() + "-";
    let M =
      (date.getMonth() + 1 < 10 ?
        "0" + (date.getMonth() + 1) :
        date.getMonth() + 1) + "-";
    let D = this.change(date.getDate()) + " ";
    return Y + M + D;
  },
  change(t) {
    if (t < 10) {
      return "0" + t;
    } else {
      return t;
    }
  },
  getInfo() { //购买商品的商品详情
    let urlStr = app.getNetAddresss("plugin.check-in-rebate.frontend.participate-in.get-detail");
    app._postNetWork({
      url: urlStr,
      data: {id:Number(this.data.id)},
      success: (resdata) => {
        var res = resdata.data;
        let data = res.data;
        if (res.result == 1) {
          data.is_error ==  true?this.data.calendarInfo.couponVal = '失败': this.data.calendarInfo.couponVal = data.continuous_day;
          this.data.calendarInfo.priceVal = data.sum_day;
          this.setData({
            partInfo:data,
            calendarInfo:this.data.calendarInfo
          })
        } else {
          if(data.activity_id) {
            wx.redirectTo({
              url: `/mircoApp/activityClock/clockDetails/clockDetails?id=${data.activity_id}&activityId=${data.activity_id}&clockStatus=0`,
            })
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getMember() {
    let urlStr = app.getNetAddresss("plugin.check-in-rebate.frontend.participate-in.get-Info");
    app._postNetWork({
      url: urlStr,
      data: {},
      success: (resdata) => {
        var res = resdata.data;
        let data = res.data;
        if (res.result == 1) {
          let infoMember = {
            priceName:'打卡天数',
            priceVal:'0',
            couponName:'连续打卡天数',
            couponVal:'0'
          };
          this.data.calendarInfo = {...infoMember,...data.member};
          this.setData({
            calendarInfo:this.data.calendarInfo,
            memberTab:this.data.memberTab,
            adminType:this.data.adminType
          })
        }
        this.getInfo();
        
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  recordListData() {
    let urlStr = app.getNetAddresss("plugin.check-in-rebate.frontend.participate-in.check-in-log");
    app._postNetWork({
      url: urlStr,
      data:this.data.query,
      success:  (resdata) => {
        let res = resdata.data;
        let data = res.data;
        if (res.result == 1) {
          let now = new Date();
          let toMonth = now.getMonth() + 1;
          let toDay = now.getDate();
          if(data.length > 0) {
            //查询是否有今天的打卡记录，没有就是未打卡状态
            let someTime = data.some((item,index) => {
              let time =  new Date(item.created_at);
              let recordMonth = time.getMonth() + 1;
              return recordMonth == toMonth && toDay == time.getDate();
            })
            this.data.dayStatus = someTime;
          }
          let that = this;
          this.setData({
            recordData: data,
            dayStatus:this.data.dayStatus,
            formatter(day){
              return that.formatters(day);
            }
          })
        } else {
          
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getiPnoneBottom() {
    let that = this;
    try {
      let value = wx.getStorageSync('iPhoneBottom');
      if (value) {
        that.setData({
          iPnoneBottomBol: true
        });
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      recordShow:false
    })
    this.getMember();
    this.recordListData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: "打卡日历",
      path: `mircoApp/activityClock/clockCalendar/clockCalendar?id=${this.data.query.id}`,
    };
  },
  onShareTimeline() {
    return {
      title: "打卡日历",
      query: `mircoApp/activityClock/clockCalendar/clockCalendar?id=${this.data.query.id}`,
    };
  }
})